//
//  PrevationV2ViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/10/15.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyUserDefaults
import SVProgressHUD

class PrevationV2ViewController: BaseViewController ,UITableViewDelegate, UITableViewDataSource{
    var tempArr = NSMutableArray()
    var mytotal: Int? = 0
    var header = MJRefreshNormalHeader()
    
    var num = Int()
    var rightBtn : UIButton! = nil
    var leftBtn : UIButton! = nil
    var mnType : NSString! = ""
    var realyType : String! = "1"
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    private lazy var myTableView:UITableView = {
        var tempheight = CGFloat()
        if UIDevice.current.isX(){
            tempheight = 104 + 24
        }else{
            tempheight = 104
        }
        
        let myTableView = UITableView(frame: CGRect(x: 0, y: tempheight, width: kScreenWidth, height: kScreenHeight), style: UITableViewStyle.grouped)
        myTableView.separatorColor = UIColor("#293163")
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.backgroundColor = UIColor.clear
        myTableView.register(PreservationV2TableViewCell.self, forCellReuseIdentifier: "cell")
        return myTableView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.makeBaseUI()
        getData()
        self.mnType = "1"
        self.title = XALanguageManager.getString(key: "Preservation")
        // Do any additional setup after loading the view.
        if UIDevice.current.isX(){
            rightBtn = UIButton.init(frame: CGRect(x: kScreenWidth/2, y: 88, width: kScreenWidth/2, height: 40))
        }else{
            rightBtn = UIButton.init(frame: CGRect(x: kScreenWidth/2, y: 64, width: kScreenWidth/2, height: 40))
        }
        
        
        rightBtn.setTitleColor(UIColor("#C1C3C9"), for: .normal)
        rightBtn.setTitleColor(UIColor("#3787FF"), for: .selected)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        rightBtn.setTitle(XALanguageManager.getString(key: "保值 N"), for: .normal)
        rightBtn.addTarget(self, action: #selector(self.rightBtnAction), for: .touchUpInside)
        self.view.addSubview(rightBtn)
        if UIDevice.current.isX(){
            leftBtn = UIButton.init(frame: CGRect(x: 0, y: 88, width: kScreenWidth/2, height: 40))
        }else{
            leftBtn = UIButton.init(frame: CGRect(x: 0, y: 64, width: kScreenWidth/2, height: 40))
        }
        
        leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        leftBtn.setTitleColor(UIColor("#C1C3C9"), for: .normal)
        leftBtn.setTitleColor(UIColor("#3787FF"), for: .selected)
        leftBtn.addTarget(self, action: #selector(self.leftBtnAction), for: .touchUpInside)
        leftBtn.setTitle(XALanguageManager.getString(key: "保值 M"), for: .normal)
        leftBtn.isSelected = true
        self.view.addSubview(leftBtn)
    }
    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
        
    }
    
    @objc func leftBtnAction(){
        // left M
        self.myTableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        self.leftBtn.isSelected = true
        self.rightBtn.isSelected = false
        mnType = "1"
        num = 1
        self.getData()
        
    }
    @objc func rightBtnAction(){
        // right N
        self.myTableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        self.rightBtn.isSelected = true
        self.leftBtn.isSelected = false
        mnType = "2"
        num = 1
        self.getNData()
    }
    
    func getNData() {
        
        MyNetwork.request(target: .baozhiNlist(user_id: Defaults[.userID]!, page: "1", limit: "1000"), success: { (result) in
            kLog(result)
            self.tempArr = []
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                let tempArr1 = NSMutableArray.yy_modelArray(with: productModel.self, json: needModel.mydata!["data"]!)
                self.mytotal = needModel.mydata!["total"]! as? Int
                
                for tempModel in tempArr1!{
                    self.tempArr.add(tempModel)
                }
                
                self.myTableView.reloadData()
                self.realyType = self.mnType as String!
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    @objc func getData() {
        
        MyNetwork.request(target: .chongNengList(user_id: Defaults[.userID]!, page: "1", limit: "1000"), success: { (result) in
            kLog(result)
        self.header.endRefreshing()
            
            self.tempArr = []
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                let tempArr1 = NSMutableArray.yy_modelArray(with: productModel.self, json: needModel.mydata!["data"]!)
                self.mytotal = needModel.mydata!["total"]! as? Int
                
                for tempModel in tempArr1!{
                    self.tempArr.add(tempModel)
                }
                self.realyType = self.mnType as String?
                self.myTableView.reloadData()
                
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    
    func makeBaseUI(){
        self.view.addSubview(myTableView)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.getData))
        
        self.myTableView.mj_header = header
    }
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell:PreservationV2TableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell")as?PreservationV2TableViewCell
        if cell == nil {
            cell = PreservationV2TableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        }
        cell.selectionStyle = .none
        cell.mnType = self.realyType;
        
        cell.model = self.tempArr[indexPath.section] as! productModel
        
        cell.numberM = String(format: "%@",(self.tempArr[indexPath.section] as! productModel).user_index!) as NSString

        return cell!
    }
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
//
//    func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
//        return CGFloat.leastNormalMagnitude
//    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return tempArr.count
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    
    // MARK: - 懒加载
//    //MARK - Private Methods
//    func makeBaseUI(){
//        //
//        self.view.backgroundColor = UIColor("#EEF0F7")
//
//
//        let backView = UIView(frame: CGRect(x: 15, y: 79, width: kScreenWidth - 30, height: 85))
//        backView.backgroundColor = UIColor.white
//        backView.layer.cornerRadius = 5
//        self.view.addSubview(backView)
//
//        let photoImageView = UIImageView.init(frame: CGRect(x: 10, y: 20, width: 44, height: 44))
//        backView.addSubview(photoImageView)
//        photoImageView.image = UIImage.init(named: "组 1@2x")
//
//        let titleLabel = UILabel.init(frame: CGRect(x: 70, y: 20, width: 44, height: 44))
//        titleLabel.text = "M"
//        titleLabel.font = UIFont.boldSystemFont(ofSize: 20)
//        backView.addSubview(titleLabel)
//
//
//        let numberButton = PPNumberButton.init(frame: CGRect(x:kScreenWidth/2 - 50 - 15 , y: 27.5, width: 110, height: 30))
//        numberButton.borderColor(UIColor.gray)
//        //开启抖动动画
//        numberButton.shakeAnimation = true
//        numberButton.maxValue = 135
//        numberButton.minValue = 1
//        //加减按钮的闭包回调
//        numberButton.numberResult { (number) in
//
//            print(number)
//        }
//
    //        backView.add@objc Subview(numberButton)
//
//
//        let myButton1 = UIButton()
//        backView.addSubview(myButton1)
//        myButton1.snp.makeConstraints { (make) in
//            make.centerY.equalTo(backView)
//            make.right.equalTo(backView).offset(-10)
//            make.size.equalTo(CGSize(width: 80, height: 30))
//        }
//        myButton1.layer.cornerRadius = 15
//        myButton1.backgroundColor = UIColor("#217AFF")
//        myButton1.alpha = 0.7
//        myButton1.titleLabel?.font = UIFont.systemFont(ofSize: 12)
//        myButton1.setTitle("Preservation", for: .normal)
//
//        //        myButton1.addTarget(self, action: #selector(SecondViewController.), for: .touchUpInside)
//
//    }
//
//    override func didReceiveMemoryWarning() {
//        super.didReceiveMemoryWarning()
//        // Dispose of any resources that can be recreated.
//    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
